/* Javascript */

function DwpCodeGenerator(){

    this.clipValid = false;
    this.imagePreviewValid = false;
    this.heightValid = false;
    this.widthValid = false;
    this.trackingIdValid = false;
    this.enableTracking = false;
    this.enableAdvertisement = false;
    
    
    this.showDiv = function(divId){
        if (obj = document.getElementById(divId)) 
            obj.style.display = 'block';
    }
    this.hideDiv = function(divId){
        if (obj = document.getElementById(divId)) 
            obj.style.display = 'none';
    }
    this.collapse = function(elementId){
        if (obj = document.getElementById(elementId)) 
            obj.style.visibility = 'collapse';
    }
    this.visible = function(elementId){
        if (obj = document.getElementById(elementId)) 
            obj.style.visibility = 'visible';
    }
    
    this.displayPlayerSettings = function(){
        this.showDiv('webplayerSettingsHeadDisplayed');
        this.showDiv('webplayerSettings');
        this.hideDiv('webplayerSettingsHeadHidden');
    }
    this.hidePlayerSettings = function(){
        this.hideDiv('webplayerSettingsHeadDisplayed');
        this.showDiv('webplayerSettingsHeadHidden');
        this.hideDiv('webplayerSettings');
    }
    this.displayGoogleAnalytics = function(){
        this.showDiv('googleAnalyticsHeadDisplayed');
        this.showDiv('googleAnalytics');
        this.hideDiv('googleAnalyticsHeadHidden');
    }
    this.hideGoogleAnalytics = function(){
        this.hideDiv('googleAnalyticsHeadDisplayed');
        this.showDiv('googleAnalyticsHeadHidden');
        this.hideDiv('googleAnalytics');
    }
    this.displayAdvertisementSettings = function(){
        this.showDiv('advertisementSettingsSectionHeadDisplayed');
        this.showDiv('advertisementSettingsSection');
        this.hideDiv('advertisementSettingsSectionHeadHidden');
    }
    this.hideAdvertisementSettings = function(){
        this.hideDiv('advertisementSettingsSectionHeadDisplayed');
        this.showDiv('advertisementSettingsSectionHeadHidden');
        this.hideDiv('advertisementSettingsSection');
    }
    
    this.showValidationMsg = function(elementId, msg){
        if (obj = document.getElementById(elementId)) {
            obj.style.display = 'block';
            obj.innerHTML = msg;
        }
    }
    this.hideValidationMsg = function(elementId){
        if (obj = document.getElementById(elementId)) {
            obj.style.display = 'none';
            obj.innerHTML = '';
        }
    }
    
    /*  Code Update */
    this.setValue = function(elementId, newValue){
        if (obj = document.getElementById(elementId)) 
            obj.value = newValue;
    }
    
    this.isChecked = function(elementId){
        if (obj = document.getElementById(elementId)) 
            return obj.checked == true;
        return false;
    }
    
    this.getValue = function(elementId){
        if (obj = document.getElementById(elementId)) 
            return obj.value;
        return null;
    }
    this.getConcatVersion = function(){
        return this.getValue('vmaj') + '.' + this.getValue('vmin') + '.' + this.getValue('vmic');
    }
    this.refresh = function(){
        /* Revalidate fields */
        if (this.getValue('url').length > 0) 
            this.validateClipUrl();
        if (this.getValue('width').length > 0) 
            this.validateWidth();
        if (this.getValue('height').length > 0) 
            this.validateHeight();
        if (this.getValue('imageurl').length > 0) 
            this.validateImageUrl();
        if (this.getValue('googleAnalyticsId').length > 0) 
            this.validateGoogleAccount();
        this.validateEnableTracking();
        this.validateAdServer();
        this.updateCode();
    }
    this.updateCode = function(){
        if (this.clipValid == true && this.heightValid == true && this.widthValid == true) {
            divName = 'divxEmbed_' + this.generateRandom(5);
            objName = 'dwp_' + this.generateRandom(4);
            $embedCode = '<script type="text/javascript" src="http://divxweb.googlecode.com/files/dwpJsLib-latest.js?nocache='+this.generateRandom(3)+'"></script>\n';
            $embedCode += '<script type="text/javascript">\n'
            $embedCode += '\tvar ' + objName + ' = new dwpPlayer(' + this.getValue('width') + ', ' + this.getValue('height') + ');\n';
            $embedCode += '\t' + objName + '.url ="' + this.getValue('url') + '";\n';
            $embedCode += '\t' + objName + '.type ="' + this.getValue('embedType') + '";\n';
            if (this.imagePreviewValid == true) {
                $embedCode += '\t' + objName + '.previewImage ="' + this.getValue('imageurl') + '";\n';
            }
            /* Following values are only populated if they differs from the default*/
            if (this.getValue('mode') != 'mini') 
                $embedCode += '\t' + objName + '.mode ="' + this.getValue('mode') + '";\n';
            if (this.isChecked('allowContextMenu') != true) 
                $embedCode += '\t' + objName + '.allowContextMenu ="false";\n';
            if (this.isChecked('autoPlay') != false) 
                $embedCode += '\t' + objName + '.autoPlay ="true";\n';
            if (this.isChecked('loop') != false) 
                $embedCode += '\t' + objName + '.loop ="true";\n';
            if ((version = this.getConcatVersion()) != '1.5.0') 
                $embedCode += '\t' + objName + '.minVersion ="' + version + '";\n';
            if (this.getValue('previewMessage') != '') {
                $embedCode += '\t' + objName + '.previewMessage ="' + this.getValue('previewMessage') + '";\n';
                if (this.getValue('previewMessageSize') != '14') 
                    $embedCode += '\t' + objName + '.previewMessageSize ="' + this.getValue('previewMessageSize') + '";\n';
            }
            if (this.isChecked('enableDebug') != false) 
                $embedCode += '\t' + objName + '.enableDebug ="true";\n';
            
            if (this.enableTracking == true) {
                $embedCode += '\t' + objName + '.enableAnalytics ="true";\n';
                $embedCode += '\t' + objName + '.googleAnalyticsId ="' + this.getValue('googleAnalyticsId').toUpperCase() + '";\n';
            }
            
            if (this.enableAdvertisement == true) {
                $embedCode += '\t' + objName + '.enableAdvertisement =true;\n';
                $embedCode += '\t' + objName + '.adServer ="' + this.getValue('adServer') + '";\n';
                if (this.getValue('adLanguage') != '--') 
                    $embedCode += '\t' + objName + '.adLanguage ="' + this.getValue('adLanguage').toUpperCase() + '";\n';
                if (this.getValue('adType') != 'all') 
                    $embedCode += '\t' + objName + '.adType ="' + this.getValue('adType') + '";\n';
                if (this.getValue('adCampaign') ) 
                    $embedCode += '\t' + objName + '.adCampaign ="' + this.getValue('adCampaign') + '";\n';   
  
            }
            if (this.getValue('bitlyLogin') && this.getValue('bitlyAPI')) {
                $embedCode += '\t' + objName + '.bitlyLogin ="' + this.getValue('bitlyLogin') + '";\n'; 
                $embedCode += '\t' + objName + '.bitlyAPIkey ="' + this.getValue('bitlyAPI') + '";\n';                     
            }
            $embedCode += '\t' + objName + '.create("' + divName + '");\n';
            $embedCode += '</script>\n<div id="' + divName + '">embed Code</div>'   
            
            this.setValue('markups', $embedCode);
            
        }
        else {
            this.setValue('markups', "The Embed code will appears here");
        }
    }
    
    /*  Validation Section  */
    this.validateClipUrl = function(){
        urlValue = this.getValue('url');
        if (urlValue.length > 0) {
            errMsg = '';
            if (this.isRemoteUrl(urlValue) == false) 
                errMsg = 'Invalid URL';
            else {
                if (this.isCompatibleMedia(urlValue) == false) {
                    errMsg = 'Invalid File Extension';
                }
            }
            if (errMsg.length != '') {
                this.showValidationMsg('clipUrlMsg', errMsg);
                this.clipValid = false;
            }
            else {
                this.hideValidationMsg('clipUrlMsg');
                this.clipValid = true;
            }
        }
        else {
            this.clipValid = false;
            this.hideValidationMsg('clipUrlMsg');
        }
    }
    
    this.validateImageUrl = function(urlValue){
        errMsg = '';
        urlValue = this.getValue('imageurl');
        if (urlValue.length > 0) {
            if (this.isRemoteUrl(urlValue) == false) 
                errMsg = 'Invalid URL';
            else {
                if (this.isValidImage(urlValue) == false) {
                    errMsg = 'Invalid File Extension';
                }
            }
            if (errMsg.length != '') {
                this.showValidationMsg('imageUrlMsg', errMsg);
                this.imagePreviewValid = false;
            }
            else {
                this.hideValidationMsg('imageUrlMsg');
                this.imagePreviewValid = true;
            }
        }
        else {
            this.hideValidationMsg('imageUrlMsg');
            this.imagePreviewValid = false;
        }
    }
    
    this.validateHeight = function(){
        height = this.getValue('height');
        if (parseInt(height) < 50 || parseInt(height) > 9999) {
            this.showValidationMsg('dimensionHeightMsg', "the 'height' must be between 50 and 9999");
            this.heightValid = false;
        }
        else {
            this.hideValidationMsg('dimensionHeightMsg');
            this.heightValid = true;
        }
    }
    this.validateWidth = function(){
        width = this.getValue('width');
        if (parseInt(width) < 50 || parseInt(width) > 9999) {
            this.showValidationMsg('dimensionWidthMsg', "the 'width' must be between 50 and 9999");
            this.widthValid = false;
        }
        else {
            this.hideValidationMsg('dimensionWidthMsg');
            this.widthValid = true;
        }
    }
    this.validateGoogleAccount = function(){
        googleAccountId = this.getValue('googleAnalyticsId').toUpperCase();
        if(googleAccountId && googleAccountId.length>0){
            var idMatch = /^UA-[0-9]/;
            if (idMatch.test(googleAccountId) != true) {
                this.showValidationMsg('googleIdMsg', "Wrong Account ID format");
                this.trackingIdValid = false;
            }
            else {
                this.hideValidationMsg('googleIdMsg');
                this.trackingIdValid = true;
            }            
        }

        
    }
    this.validateEnableTracking = function(){
        /* If already activated, deactivate */
        if (document.getElementById('enableAnalytics').checked == true) {
            this.validateGoogleAccount();
            if (this.trackingIdValid == true) {
                this.enableTracking = true;
                this.hideValidationMsg('enableTrackMsg');
            }
            else {
                this.showValidationMsg('enableTrackMsg', "You must provide a valid Account Id");
                this.enableTracking = false;
                document.getElementById('enableAnalytics').checked = false;
            }
        }
        else {
            this.enableTracking = false;
            this.hideValidationMsg('enableTrackMsg');
        }
    }
    
    
    this.validateAdServer = function(urlValue){
        urlValue = this.getValue('adServer');
        if (urlValue.length > 0) {
            errMsg = '';
            if (this.isRemoteUrl(urlValue) == false) {
                this.showValidationMsg('adServerMsg', 'Invalid AdServer URL');
                this.enableAdvertisement = false;
                
            }
            else {
                this.hideValidationMsg('adServerMsg');
                this.enableAdvertisement = true;
            }
        }
        else {
            this.enableAdvertisement = false;
            this.hideValidationMsg('adServerMsg');
        }
                
    }

    this.isRemoteUrl = function(urlValue){
        var url_match = /^(http(s?):\/\/{1})+(([a-z0-9]+|([a-z0-9]+[-]+[a-z0-9]+))[.])+(([a-z0-9]+|([a-z0-9]+[-]+[a-z0-9]+)))/;
        return url_match.test(urlValue) == true;
    }
    
    this.isCompatibleMedia = function(urlValue){
        var url_match = /^.*\.(divx|mkv|avi)$/;
        return url_match.test(urlValue.toLocaleLowerCase()) == true;
    }
    
    this.isValidImage = function(urlValue){
        var url_match = /^.*\.(jpg|png|gif)$/;
        return url_match.test(urlValue.toLocaleLowerCase()) == true;
    }
    this.isset = function(elementId){
        if (obj - document.getElementById(elementId)) 
            if (obj.value.length > 0) 
                return true
        return false;
    }
    
    this.validate = function(el){
        switch (el.id) {
            case 'url':
                this.validateClipUrl();
                break;
            case 'width':
                this.validateWidth();
                break;
            case 'height':
                this.validateHeight();
                break;
            case 'imageurl':
                this.validateImageUrl();
                break;
            case 'googleAnalyticsId':
                this.validateGoogleAccount();
                break;
            case 'enableAnalytics':
                this.validateEnableTracking();
                break;
            case 'adServer':
                this.validateAdServer();
                break;
                
        }
        this.updateCode();
    }
    
    /* Generate random values */
    this.generateRandom = function(length){
        chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
        pass = "";
        
        for (x = 0; x < length; x++) {
            i = Math.floor(Math.random() * 62);
            pass += chars.charAt(i);
        }
        return pass;
    }
       
}



